package mbsl.ui;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;

import mbsl.util.Cache;

public final class ImageLoader {
	/** Loads a named picture from mbsl.art.  The path and .png are implied. */
	public static Image getImage(Device pDevice, String pName) {
		return getImage(pDevice, pName + ".png", "/mbsl/art/");
	}
	/**
	 * Attempts to load the picture with the provided name from the provided location.
	 */
	public static Image getImage(Device pDevice, String pName, String pLocation) {
		if (mCache == null)
			mCache = new Cache<Image>();
		
		StringBuilder name = new StringBuilder(pName.length() + 1 + pLocation.length());
		
		name.append(pLocation);
		
		if (!pLocation.endsWith("/"))
			name.append("/");
		
		name.append(pName);

		int hash = new HashCodeBuilder().append(name).toHashCode(); 
		
		Image image = mCache.get(hash);
		
		if (image == null) {
			InputStream stream = Image.class.getResourceAsStream(name.toString());
			
			if (stream == null)
				return null;
			
			try {
				image = new Image(pDevice, stream);
			} catch (SWTException pE) {
				return null;
			} finally {
				try {
					stream.close();
				} catch (IOException pE) {}
			}
			
			mCache.put(hash, image);
		}
		
		return image;
	}
	
	private static Cache<Image> mCache;
	
	private ImageLoader() {}
}
